<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    // 判断当前浏览器是否支持WebSocket
    if  ('WebSocket' in window) {
        socket = new WebSocket("ws://localhost:8081/hello");
        // 相当于channelRead0，ev收到服务器端回送的消息
        socket.onmessage = function (event) {
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + event.data;
        }

        // 相当于连接开启
        socket.onopen = function () {
            var message = document.getElementById("responseText");
            message.value = "连接开启。。。";
        }

        // 相当于连接关闭
        socket.onclose = function () {
            var message = document.getElementById("responseText");
            message.value = message.value + "\n" + "连接关闭了。。。";
        }
    } else {
        alert("Not support websocket")
    }

    // 发送消息到服务器
    function send(message) {
        // 先判断socket是否创建好
        if (!window.socket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else  {
            alert("连接没有开启");
        }
    }
</script>
<form onsubmit="return false">
    <textarea name="message" style="height: 300px;width: 500px;"></textarea>
    <input type="button" value="发送消息" onclick="send(this.form.message.value)">
    <textarea id="responseText" style="height: 300px;width: 500px;"></textarea>
    <input type="button" value="清空" onclick="document.getElementById('responsetext').value=''">"
</form>
</body>
</html>